import React, { useState, useEffect } from 'react';
import { LoadingOutlined, } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import { SketchPicker } from 'react-color';
import { Layout, Form, Row, Col, Input, Radio, Popover, DatePicker, Button, Slider, InputNumber, message, Select } from 'antd';
import moment from 'moment';
import { history } from 'umi';
import { PlanItemParam, PlanTimeListParams, ProgramListParams } from '../Plan/data.d';
import { FormInstance } from 'antd/lib/form';
import '../../assets/css/index.css';
import styles from './index.less';
import { programDetail } from '../Program/service';
import { repackPlan } from '../Plan/service';

const { Content } = Layout;
const layout = {
    labelCol: { span: 10 },
    wrapperCol: { span: 14 },
};

const { Option } = Select;

const { RangePicker } = DatePicker;
const antIcon = <LoadingOutlined style={{ fontSize: 12 }} spin />;

const formRef = React.createRef<FormInstance>();
let programIds = new Array(); //节目列表 --按时段播放
let keepProgramIds = new Array(); //节目列表 --持续播放
let status = "add";

const disabledDate = (current: any) => {
    return current < moment(new Date(moment().format('YYYY/MM/DD')));
}

const animationDurant = (speed:String, width:number) => {
    const gallery_width = 768;
    let animation_durant = 0;
    if(speed == 'speed1'){//快
        animation_durant = (gallery_width + width)/91;
    }else if(speed == 'speed2'){//中
        animation_durant = (gallery_width + width)/61;
    }else{//慢
        animation_durant = (gallery_width + width)/31;
    }
    return animation_durant;
}

const CreateNotice: React.FC<{}> = (props) => {
    const [planInfo, setPlanInfo] = useState<PlanItemParam>({});
    const [defaultPlan, setDefaultPlan] = useState<boolean>(false); //默认计划
    const [timeList, handleTimeList] = useState<PlanTimeListParams[]>([]); //循环时间段列表 -- 按时段播放
    const [refresh, handleRefresh] = useState<boolean>(false); //是否刷新列表
    const [programList, handleProgramList] = useState<ProgramListParams[]>([]); //节目列表
    const [values, setValues] = useState<ProgramListParams>(); //循环项值对象
    const [publishWayDisabled, handlePublishWayDisabled] = useState<boolean>(false);
    const [planDateDisabled, handlePlanDateDisabled] = useState<boolean>(false);
    const [programSelectIndex, handleProgramSelectIndex] = useState<number>(0); //循环时间段列表 -- 选中状态
    const [programErrorIndex, handleProgramErrorIndex] = useState<number>(); //循环时间段列表【非空】 -- 选中状态

    const [text, setText] = useState<String>('11'); //循环项值对象
    const [fontColor, handleSetFontColor] = useState<any>({ r: '255', g: '255', b: '255', a: '1' });
    const [fontSize, handleSetFontSize] = useState<number>(14);
    const [backgroundColor, handleSetBackGroundColor] = useState<any>({ r: '0', g: '0', b: '0', a: '0' });
    const [backgroundHeight, handleSetBackgroundHeight] = useState<number>(76);
    const [fontPosition, handleSetFontPosition] = useState<String>('flex-start');
    const [speed, handleSetSpeed] = useState<String>('speed2');

    const [repackPlanList, setRepackPlanList] = useState<Array<any>>([]); //循环时间段列表 -- 按时段播放
    const [repackModalVisible, handleRepackModalVisible] = useState<boolean>(false);
    const [repackFinish, handleRepackFinish] = useState<boolean>(false);
    const [form] = Form.useForm();

    const repackPlanRequest = (list: Array<any>) => {
        let resList = new Array;
        function startRequest() {
            //定义counts，用来收集请求的次数，（也可以用resList的length进行判断）
            let counts = 0;
            return function requestFunc() {
                if (counts == list.length) {
                    handleRepackFinish(true);
                    localStorage.removeItem("programInfo");
                    localStorage.removeItem("planUpdate");
                    return;
                }
                let arg = list[counts].name;
                let a = new Promise((res, rej) => {
                    const id = list[counts].id;
                    repackPlan(id).then(result => {
                        if (result && result.code === 200) {
                            list[counts].status = "success";
                            res(true);
                        } else {
                            list[counts].status = "failed";
                            res(false);
                        }
                        setRepackPlanList(list.concat());

                    })
                })
                //无论成功或者失败都要进行下一次，以免阻塞，成功请求的末尾有s标志，失败的末尾有f标志
                a.then(() => {
                    counts++;
                    resList.push(arg + ' s');
                    requestFunc(list[counts])
                }).catch(err => {
                    // resList.push(arg + 'f');
                    //递归调用
                    // console.log("======递归调用==========")
                    // requestFunc(list[counts])
                    console.log(err)
                })
            }
        }
        let start = startRequest();
        start(list[0]);
    }

    useEffect(() => {
        setTimeout(function () {
            const programInfo = localStorage.getItem("programInfo");
            if (programInfo) {
                const programId = JSON.parse(programInfo)?.id;
                const planUpdate = localStorage.getItem("planUpdate");
                if (planUpdate == "true") {
                    if (programId) {
                        new Promise((resolve, reject) => {
                            programDetail(programId)
                                .then((res) => {
                                    if (res && res.code === 200) {
                                        let data = res.data;
                                        const list = data.plans;
                                        if (list && list.length > 0) {
                                            const planList = list.map(item => { return { id: item.id, name: item.name, status: 'spinning' } });
                                            if (planList.length > 0) {
                                                setRepackPlanList(planList);
                                                handleRepackModalVisible(true);
                                                repackPlanRequest(planList);
                                            }
                                        } else {
                                            localStorage.removeItem("programInfo");
                                            localStorage.removeItem("planUpdate");
                                        }
                                        resolve(true);
                                    } else {
                                        message.error('请求失败，' + res.message);
                                        resolve(false);
                                    }
                                })
                                .catch((error) => {
                                    message.error('请求失败');
                                    reject(error);
                                });
                        });
                    }
                } else {
                    localStorage.removeItem("programInfo");
                    localStorage.removeItem("planUpdate");
                }
            } else {
                localStorage.removeItem("planUpdate");
            }
        }, 500)
    }, []);

    useEffect(() => { //只在第一次加载时执行该函数
        //初始化信息
        if (props.location.state) {
            status = "edit";
            setPlanInfo(props.location.state);
            if (planInfo?.name) {
                planInfo?.publishWay === 1 && planInfo?.publishDatetime ? handlePublishWayDisabled(true) : handlePublishWayDisabled(false);
                const playConfig = JSON.parse(planInfo?.playConfig);
                handleProgramList(playConfig[0].programList);
                if (planInfo?.playMode === 0) {//持续播放
                    handlePlanDateDisabled(true);
                    keepProgramIds = playConfig[0].programList.concat();
                    setValues(playConfig[0].programList);
                } else {//按时段播放
                    keepProgramIds = [];
                    handleTimeList(playConfig);
                    handlePlanDateDisabled(false);
                }
                setDefaultPlan(planInfo?.defaultPlan);
                formRef.current?.setFieldsValue({
                    "name": planInfo?.name,
                    "defaultPlan": planInfo?.defaultPlan,
                    "playStrategy": planInfo?.playStrategy,
                    "publishType": planInfo?.publishType,
                    "playMode": planInfo?.playMode,
                    "plan-date-picker": planInfo?.startDatetime ? [moment(planInfo?.startDatetime), moment(planInfo?.endDatetime)] : null,
                    "publishWay": planInfo?.publishWay,
                    "publishDatetimeType": planInfo?.publishDatetime ? "custom" : "default",
                    "plan-time-picker": planInfo?.publishDatetime ? moment(planInfo?.publishDatetime) : null,
                    "noticeContent": planInfo?.noticeContent,
                });
                if (planInfo?.flag) {
                    console.log("发布");
                    keepProgramIds = playConfig[0].programList.concat();
                    setValues(playConfig[0].programList);
                }
            }
        } else {
            status = "add";
            programIds = [];
            keepProgramIds = [];
        }
        let length = planInfo?.noticeContent ? planInfo?.noticeContent.length : 0;
        const showCunt = document.querySelector("textarea").parentNode;
        showCunt.setAttribute("data-count", length + " / 300");
        showCunt?.addEventListener("keyup", function () {
            length = this.querySelector("textarea").value.length;
            this.setAttribute("data-count", length + " / 300");
        });
    }, [planInfo]);

    useEffect(() => {
        if (refresh) {
            timeList[index] = JSON.parse(JSON.stringify(values));
            handleRefresh(false);
        }
    });

    useEffect(() => {
        if (!planDateDisabled) {
            if (timeList.length > 0) {
                handleProgramSelectIndex(0); //默认选中第一个
                handleProgramList(timeList[0].programList);
            } else {
                handleProgramList([]);
            }
        }
    }, [timeList]);

    useEffect(() => {
        const textarea = document.getElementById("notice-text");
        var width = textarea.offsetWidth;
        var animation_durant = animationDurant(speed,width);
        console.log(width,animation_durant);
        textarea.style.animation = `fadeInLeft ${animation_durant}s linear infinite`;
    }, [text,speed,fontSize]);
    
    const handleFinish = (values: { [key: string]: any }) => { //下一步values
        console.log(values)
        console.log(moment(values.noticeTime[0],'HH:mm:ss'))
        // if (defaultPlan && !planDateDisabled) {
        //     message.warn('默认计划不能按时段播放');
        //     return;
        // }
        // //当发布方式：定时发布 并且 发布时间：自定义时间时
        // if (values.publishDatetimeType && values.publishDatetimeType == "custom") {
        //     if (planInfo.publishDatetime && planInfo.endDatetime) {
        //         if (planInfo.publishDatetime > planInfo.endDatetime) {
        //             message.warn('自定义时间要在计划日期时间段内');
        //             return;
        //         } else {
        //             const date = new Date();
        //             const year = date.getFullYear();
        //             const month = date.getMonth() + 1;
        //             const day = date.getDate();
        //             const hour = date.getHours();
        //             const minutes = date.getMinutes() + 1;
        //             let currentDate = year.toString() + '-' +
        //                 (month >= 10 ? month.toString() : "0" + month) + '-' +
        //                 (day >= 10 ? day.toString() : "0" + day) + " " +
        //                 (hour >= 10 ? hour.toString() : "0" + hour) + ":" +
        //                 (minutes >= 10 ? minutes.toString() : "0" + minutes) + ":00";
        //             if (planInfo.publishDatetime < currentDate) {
        //                 message.warn('自定义时间要在当前时间之后');
        //                 return;
        //             }
        //         }
        //     }
        // }

        

        // for (var key in values) {
        //     if (key != "plan-time-picker" && key != "plan-date-picker") {
        //         planInfo[key] = values[key];
        //     }
        // }
        //提取节目列表id
        // programIds = [];
        // if (planDateDisabled) {//持续播放
        //     for (let i in keepProgramIds) {
        //         const programItem = keepProgramIds[i];
        //         programIds.push(parseInt(programItem.id));
        //     }
        // } else { //按时段播放
        //     for (let i in timeList) {
        //         const timeItem = timeList[i];
        //         const programItems = timeItem.programList;
        //         if (programItems.length == 0) {
        //             message.warn('第' + (parseInt(i) + 1) + '个循环时间段请添加关联节目');
        //             handleProgramErrorIndex(i);
        //             return;
        //         }
        //         for (let j in programItems) {
        //             const programItem = programItems[j];
        //             programIds.push(parseInt(programItem.id));
        //         }
        //     }
        // }

        // var newSet = new Set(programIds);
        // programIds = Array.from(newSet);
        // if (programIds.length == 0) {
        //     message.warn('请添加关联节目');
        //     return;
        // }
        // if (defaultPlan && programIds.length > 1) {
        //     message.warn('默认计划只能添加一个节目');
        //     return;
        // }
        // planInfo["programIds"] = programIds.toString();

        // //发布时间 默认事件去掉publishDatetime
        // if (planInfo["publishDatetimeType"] === "default") {
        //     planInfo["publishDatetime"] = null;
        // }

        // if (planDateDisabled) {//持续播放
        //     // planInfo["publishDatetime"] = null;
        //     const temp = new Object();
        //     const array = new Array();
        //     temp["programList"] = keepProgramIds;
        //     temp["startTime"] = "00:00:00",
        //         temp["endTime"] = "23:59:59",
        //         array.push(temp);
        //     planInfo["playConfig"] = JSON.stringify(array);
        // } else {//按时段播放
        //     planInfo["playConfig"] = JSON.stringify(timeList);
        //     keepProgramIds = [];
        // }
        // console.log(planInfo)
        // history.push({ pathname: '/plan/list/equipment/', state: planInfo });
    };

    const playIntervalChange = (obj: any) => { //播放模式
        const value = obj.target.value;
        if (value === 0) { //持续播放
            handlePlanDateDisabled(true);
            handleProgramList(keepProgramIds);
        } else if (value === 1) { //按时段播放
            handlePlanDateDisabled(false);
            if (timeList.length > 0) {
                if (timeList[0].programList) {//节目列表有值
                    handleProgramList(timeList[0].programList);
                    handleProgramSelectIndex(0);
                    handleProgramErrorIndex(-1);
                }
            } else {
                handleProgramList([]);
            }
        }
        formRef.current?.setFieldsValue({ "playMode": value });
    }

    const onTextareaChange = (e:any) => {
        setText(e.target.value);
    }

    const handleChangeFontColor = (color) => {
        console.log(color.rgb);
        handleSetFontColor(color.rgb);
    };

    const fontColorContent = (
        <SketchPicker color={fontColor} onChangeComplete={handleChangeFontColor} />
    );

    const onFontSizeChange = (fontSize: number) => {
        handleSetFontSize(fontSize);
    };

    const handleChangeBackgroundColor = (color) => {
        handleSetBackGroundColor(color.rgb);
    };

    const backgroundColorContent = (
        <SketchPicker color={backgroundColor} onChangeComplete={handleChangeBackgroundColor} />
    );

    const onBackgroundHeightChange = (height: number) => {
        handleSetBackgroundHeight(height);
    };

    const onFontPositionChange = (position: String) => {
        handleSetFontPosition(position);
    };

    const onSpeedChange = (speed: String) => {
        handleSetSpeed(speed);
    };

    const noticeTimePickChange = (value,time) =>{
        console.log('选择的时间：', time)
    }
    return (
        <PageContainer title={status == "add" ? "新建公告" : "编辑公告"}>
            <Content className={styles.site_layout_background}>
                <Form {...layout} ref={formRef} form={form} scrollToFirstError onFinish={handleFinish}>
                    <Row>
                        <Col span={24} className={styles.notice} >
                            <Form.Item noStyle>
                                <div className="left">
                                    <div className='gallery'>
                                        <div className='wrapper' style={{ alignItems: fontPosition }}>
                                            <div className='notice-content' style={{ display: 'flex', width: '100%', height: backgroundHeight, backgroundColor: `rgba(${backgroundColor.r}, ${backgroundColor.g}, ${backgroundColor.b}, ${backgroundColor.a})` }}>
                                                <p id="notice-text" className={`${speed}`} style={{ color: `rgba(${fontColor.r}, ${fontColor.g}, ${fontColor.b}, ${fontColor.a})`, fontSize: fontSize, height: backgroundHeight, lineHeight: backgroundHeight + 'px'}}> {text}</p>
                                            </div>
                                        </div>
                                    </div>
                                    <Col span={24}>
                                        <Form.Item
                                            name="noticeContent"
                                            rules={[{ required: true,max: 300,message:'公告内容不能为空，并且最多300个字符' }]}
                                            className={styles.noticeContent}
                                        >
                                            <Input.TextArea rows={4} style={{ resize: "none" }} placeholder="请输入公告内容" maxLength={300} onChange={(e)=>{onTextareaChange(e);}} />
                                        </Form.Item>
                                    </Col>
                                </div>
                                <div className="right">
                                    <Row>
                                        <Col span={24}>
                                            <Form.Item
                                                name="fontColor"
                                                label="字体颜色"
                                                initialValue={fontColor}
                                            >
                                                <Popover content={fontColorContent} title="字体颜色" trigger="click">
                                                    <span className='colorArea' style={{ background: fontColor }}></span>
                                                </Popover>
                                            </Form.Item>
                                        </Col>
                                        <Col span={24} className="endLine">
                                            <Form.Item
                                                name="fontSize"
                                                label="字体大小"
                                                initialValue={fontSize}
                                            >
                                                <Slider
                                                    min={12}
                                                    max={100}
                                                    onChange={onFontSizeChange}
                                                    value={typeof fontSize === 'number' ? fontSize : 0}
                                                />
                                                <InputNumber
                                                    min={12}
                                                    max={100}
                                                    style={{ marginLeft: '10px' }}
                                                    value={fontSize}
                                                    onChange={onFontSizeChange}
                                                />
                                            </Form.Item>
                                        </Col>
                                        <Col span={24} style={{ marginTop: 24 }}>
                                            <Form.Item
                                                name="backgroundColor"
                                                label="背景颜色"
                                                initialValue={backgroundColor}
                                            >
                                                <Popover content={backgroundColorContent} title="背景颜色" trigger="click">
                                                    <span className='colorArea' style={{ background: backgroundColor }}></span>
                                                </Popover>
                                            </Form.Item>
                                        </Col>
                                        <Col span={24} className="endLine">
                                            <Form.Item
                                                name="backgroundHeight"
                                                label="背景高度"
                                                initialValue={backgroundHeight}
                                            >
                                                <Slider
                                                    min={12}
                                                    max={822}
                                                    onChange={onBackgroundHeightChange}
                                                    value={typeof backgroundHeight === 'number' ? backgroundHeight : 0}
                                                />
                                                <InputNumber
                                                    min={12}
                                                    max={822}
                                                    style={{ marginLeft: '10px' }}
                                                    value={backgroundHeight}
                                                    onChange={onBackgroundHeightChange}
                                                />
                                            </Form.Item>
                                        </Col>
                                        <Col span={24} style={{ marginTop: 24 }}>
                                            <Form.Item
                                                name="fontPosition"
                                                label="文字位置"
                                                initialValue={fontPosition}
                                            >
                                                <Select style={{ width: 88 }} placeholder="请选择文字位置" onChange={onFontPositionChange}>
                                                    <Option value="flex-start">上</Option>
                                                    <Option value="center">中</Option>
                                                    <Option value="flex-end">下</Option>
                                                </Select>
                                            </Form.Item>
                                        </Col>
                                        <Col span={24} className="endLine">
                                            <Form.Item
                                                name="speed"
                                                label="播放速度"
                                                initialValue={speed}
                                            >
                                                <Select style={{ width: 88 }} placeholder="请选择播放速度" onChange={onSpeedChange}>
                                                    <Option value="speed1">快</Option>
                                                    <Option value="speed2">中</Option>
                                                    <Option value="speed3">慢</Option>
                                                </Select>
                                            </Form.Item>
                                        </Col>
                                        <Col span={24} style={{ marginTop: 24 }}>
                                            <Form.Item
                                                name="playMode"
                                                label="播放模式"
                                                initialValue={1}
                                            >
                                                <Radio.Group defaultValue={1} onChange={playIntervalChange}>
                                                    <Radio value={1}>按时段播放</Radio>
                                                    <Radio value={0}>持续播放</Radio>
                                                </Radio.Group>
                                            </Form.Item>
                                            {planDateDisabled == false ? (
                                                <Form.Item
                                                    className='notice-time'
                                                    name="noticeTime"
                                                    label="公告日期"
                                                    rules={[
                                                        { required: true },
                                                        // {
                                                        //     validator: (rule, value, callback) => {
                                                        //         if (!value) {
                                                        //             callback();
                                                        //         }
                                                        //         // const endDatetime = planInfo?.endDatetime?.split(" ")[0].replace(/-/g, "");
                                                        //         // console.log(endDatetime);

                                                        //         // if (endDatetime) {
                                                        //         //     const date = new Date();
                                                        //         //     const year = date.getFullYear();
                                                        //         //     const month = date.getMonth() + 1;
                                                        //         //     const day = date.getDate();
                                                        //         //     let currentDate = year.toString() + (month >= 10 ? month.toString() : "0" + month) + (day >= 10 ? day.toString() : "0" + day);
                                                        //         //     if (parseInt(endDatetime) >= parseInt(currentDate)) {
                                                        //         //         callback();
                                                        //         //     } else {
                                                        //         //         callback('公告日期截止日要在当前时间之后');
                                                        //         //     }
                                                        //         // }
                                                        //     },
                                                        // }
                                                    ]} >
                                                    <RangePicker 
                                                        showTime 
                                                        showNow={true} 
                                                        disabledDate={disabledDate}
                                                        // format={'YYY-MM-DD HH:mm'}
                                                    onChange={noticeTimePickChange} 
                                                    />
                                                </Form.Item>
                                            ) : null}
                                        </Col>
                                    </Row>
                                </div>
                            </Form.Item>
                        </Col>
                        <Col span={24} className={styles.footer}>
                            <Form.Item noStyle>
                                <Button style={{ marginRight: 50 }} onClick={() => history.push('/Program/noticeList/')}>取消</Button>
                                <Button type="primary" htmlType="submit">下一步</Button>
                            </Form.Item>
                        </Col>
                    </Row>
                </Form>
            </Content>
            {/* <Modal
                title="更新计划"
                visible={repackModalVisible}
                footer={repackFinish ? <Button onClick={() => handleRepackModalVisible(false)}>关闭</Button> : null}
                closable={false}
                className={styles1.RepackPlanModel}
            >
                {repackPlanList.map(item => {
                    return item.status == 'spinning' ? (
                        <p key={item.id}>计划 {item.name} 更新中，请稍后...<Spin indicator={antIcon} style={{ marginLeft: 10 }} /></p>
                    ) : (
                        item.status == 'success' ? (
                            <p key={item.id}>计划 {item.name} 更新完成<CheckCircleTwoTone twoToneColor="#52c41a" style={{ marginLeft: 10 }} /></p>
                        ) : (
                            <p key={item.id}>计划 {item.name} 更新失败<CloseCircleTwoTone twoToneColor="#ff4d4f" style={{ marginLeft: 10 }} /></p>
                        )
                    )
                }
                )}
            </Modal> */}

        </PageContainer>
    );
};

export default CreateNotice;